#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#

import socket
import struct
import subprocess


class Ftp(object):
    def __init__(self, conn, file_name):
        self.conn = conn
        self.file_name = file_name

    def list(self):
        res = subprocess.Popen("dir", shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        stdout = res.stdout.read()
        stderr = res.stderr.read()
        length = len(stdout) + len(stderr)
        header_size = struct.pack("i", length)
        print(header_size)
        self.conn.send(header_size)
        self.conn.send(stdout)
        self.conn.send(stderr)

    def upload(self):
        self.conn.send("upload".encode("utf-8"))

    def download(self):
        self.conn.send("download".encode("utf-8"))


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.bind(("0.0.0.0", 2008))
    server.listen(1)
    while True:
        conn, addr = server.accept()
        print(addr)
        while True:
            command = conn.recv(1024).decode("utf-8")
            command_chiose = command.split(" ")[0]
            if hasattr(Ftp, command_chiose):
                print("11111111")
                ftp = Ftp(conn, command.split(" ")[1])
                print(command_chiose)
                getattr(ftp, command_chiose)()
            else:
                conn.send("not command".encode("utf-8"))
        conn.close()
